/**
 * 
 */
package org.vsg.stock.presentation;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.vsg.common.jobscheduler.service.JobService;
import org.vsg.common.jobscheduler.service.QuartzService;
import org.vsg.common.jobscheduler.vo.Argument;
import org.vsg.common.jobscheduler.vo.JobInfo;
import org.vsg.common.jobscheduler.vo.TriggerJob;
import org.vsg.common.web.json.ListResult;
import org.vsg.common.web.json.SubmitResult;

/**
 * @author vison
 *
 */
@Controller
public class StockSchedulerController {

	private final static Logger logger = LoggerFactory.getLogger(StockSchedulerController.class);
	
	private final static String MODULE_NAME = "stock";
	
	@Resource
	private JobService jobService;
	
	@Resource
	private QuartzService quartzService;

	@RequestMapping(value="/"+MODULE_NAME+"/jobSchedule.do")	
	public String jobSchedule(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		
		
        return "/stock/job-schedule";
    }
	

	@RequestMapping(value="/"+MODULE_NAME+"/showScheduleArgs.do")	
	public ModelAndView showScheduleArgs(String code , HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		List<Argument> args =  jobService.getJobInfoArgumentByCode(code);
		
		// --- covert to dyna object
		Map map = new HashMap();
		if (args != null ) {
			for (Iterator<Argument> argsIter = args.iterator() ; argsIter.hasNext() ; ) {
				Argument arg = argsIter.next();
				map.put( arg.getName() , arg.getValue() );
			}
			
		}

		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setData( map );
		
        // --- convert model to data format
		JSONObject jsonObj = JSONObject.fromObject(submitResult ); 

		/**
		 * defined the module and view handle
		 */
		ModelAndView mav = new ModelAndView();
        mav.setViewName("result");	// view name
        
        mav.addObject("json",jsonObj);
        
        logger.info(jsonObj.toString());
        return mav;
    }	
	
	
	@RequestMapping(value="/"+MODULE_NAME+"/avaiScheduler.do")	
	public ModelAndView  avaiScheduler(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		List<JobInfo> avaiJobs = jobService.listModuleAvaiRegJobs();
		
		// ----- add map to json object ----
		ListResult lr = new ListResult();
		lr.setResults(avaiJobs.size());
		lr.setRows(avaiJobs);
		
		/**
		 * defined the module and view handle
		 */
		ModelAndView mav = new ModelAndView();
        mav.setViewName("json");	// view name

        
        // --- convert model to data format
		JsonConfig jcfg = new JsonConfig();
		//jcfg.registerJsonValueProcessor(java.sql.Timestamp.class,new JsTimestampJsonValueProcessor());
		JSONObject jsonObj = JSONObject.fromObject(lr, jcfg);        
        mav.addObject("json",jsonObj);
        
        logger.info(jsonObj.toString());
        return mav;
	}
	
	
	@RequestMapping(value="/"+MODULE_NAME+"/runningScheduler.do")	
	public ModelAndView  runningScheduler(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		List<TriggerJob> triggers = jobService.listAllScheduledJobsByGroup("stock");
		
		// ----- add map to json object ----
		ListResult lr = new ListResult();
		lr.setResults(triggers.size());
		lr.setRows(triggers);
		
		/**
		 * defined the module and view handle
		 */
		ModelAndView mav = new ModelAndView();
        mav.setViewName("json");	// view name

        
        // --- convert model to data format
		JsonConfig jcfg = new JsonConfig();
		//jcfg.registerJsonValueProcessor(java.sql.Timestamp.class,new JsTimestampJsonValueProcessor());
		JSONObject jsonObj = JSONObject.fromObject(lr, jcfg);        
        mav.addObject("json",jsonObj);
        
        logger.info(jsonObj.toString());
        return mav;
	}	
	
	@RequestMapping(value="/"+MODULE_NAME+"/addSchedule.do")		
	public ModelAndView addSchedule(short triggerType , HttpServletRequest request) throws Exception {
		
		String jobCode = request.getParameter("jobCode");
		
		String startDateTime = request.getParameter("startDateTime");
		String endDateTime = request.getParameter("endDateTime");
		String repeatCountStr = request.getParameter("repeatCount");
		String repeatIntervalStr = request.getParameter("repeatInterval");
		String cronPattern = request.getParameter("cronPattern");
		
		// --- get the argument from handle ---
		Enumeration<String> enume = request.getParameterNames();
		JobDataMap jobArgs = new JobDataMap();
		while (enume.hasMoreElements()) {
			String paramName = enume.nextElement();
			if (paramName.startsWith("sca_")) {
				jobArgs.put( paramName.replaceFirst("sca_", "") , request.getParameter( paramName) );
			}
		}
		
		JobInfo jobInfo = jobService.getModuleAvaiRegJob( jobCode );

		Calendar rightNow = Calendar.getInstance();		
		
		// --- build the job detail ---
		JobDetail jobDetail = new  JobDetail(jobInfo.getCode() + "_" + rightNow.getTimeInMillis(), MODULE_NAME , jobInfo.getJobClass());
		jobDetail.setJobDataMap(jobArgs);
		
		// --- get the current time
		String triggerCode = jobInfo.getCode() +"_t_" + rightNow.getTimeInMillis();
		
		
		// --- simple trigger type ---
		Trigger trigger = null;
		
		if (triggerType == 1) {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			
			df.parse(startDateTime);
			
			SimpleTrigger strigger = new SimpleTrigger(triggerCode ,MODULE_NAME, df.parse(startDateTime)) ;

			
			if (endDateTime != null && !endDateTime.equals("")) {
				strigger.setEndTime( df.parse(endDateTime) );
			}
			
			if ( repeatCountStr != null && !repeatCountStr.equals("") 
					&& 
					repeatIntervalStr != null && !repeatIntervalStr.equals("")) {
				strigger.setRepeatCount( Integer.parseInt( repeatCountStr ) );
				strigger.setRepeatInterval( Long.parseLong( repeatIntervalStr ) );
			}
			
			trigger = strigger;

		}
		else if (triggerType == 2) {
			CronTrigger cTrigger = new CronTrigger(triggerCode ,MODULE_NAME , cronPattern);
			trigger = cTrigger;
		}
		
		// --- set the description
		trigger.setDescription( jobInfo.getName() );

		// ---- defined the new jboect and title
		quartzService.definedJob(jobDetail, trigger);
		
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setData( new HashMap() );
		
        // --- convert model to data format
		JSONObject jsonObj = JSONObject.fromObject(submitResult ); 

		/**
		 * defined the module and view handle
		 */
		ModelAndView mav = new ModelAndView();
        mav.setViewName("result");	// view name
        
        mav.addObject("json",jsonObj);
        
        logger.info(jsonObj.toString());
        return mav;		
	}

	@RequestMapping(value="/"+MODULE_NAME+"/resumeSchedule.do")	
	public ModelAndView resumeSchedule(String[] triggerNames , String[] triggerGroups) throws Exception {
		// ---- defined the new jboect and title
		
		if (triggerNames != null) {
			// --- parse the name ---
			for (int i = 0 ; i < triggerNames.length ; i++) {
				String triggerName = triggerNames[i];
				String triggerGroup = triggerGroups[i];

				quartzService.resumeJobTrigger(triggerName, triggerGroup);
			}
		}
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setData( new HashMap() );
		
        // --- convert model to data format
		JSONObject jsonObj = JSONObject.fromObject(submitResult ); 

		/**
		 * defined the module and view handle
		 */
		ModelAndView mav = new ModelAndView();
        mav.setViewName("result");	// view name
        
        mav.addObject("json",jsonObj);
        
        logger.info(jsonObj.toString());
        return mav;	
	}
	
	
	@RequestMapping(value="/"+MODULE_NAME+"/stopSchedule.do")	
	public ModelAndView stopSchedule(String[] triggerNames , String[] triggerGroups) throws Exception {
		// ---- defined the new jboect and title
		
		if (triggerNames != null) {
			// --- parse the name ---
			for (int i = 0 ; i < triggerNames.length ; i++) {
				String triggerName = triggerNames[i];
				String triggerGroup = triggerGroups[i];

				quartzService.stopJobTrigger(triggerName, triggerGroup);
			}
		}
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setData( new HashMap() );
		
        // --- convert model to data format
		JSONObject jsonObj = JSONObject.fromObject(submitResult ); 

		/**
		 * defined the module and view handle
		 */
		ModelAndView mav = new ModelAndView();
        mav.setViewName("result");	// view name
        
        mav.addObject("json",jsonObj);
        
        logger.info(jsonObj.toString());
        return mav;	
	}

	@RequestMapping(value="/"+MODULE_NAME+"/removeSchedule.do")	
	public ModelAndView removeSchedule(String[] triggerNames , String[] triggerGroups) throws Exception {
		// ---- defined the new jboect and title
		if (triggerNames != null) {
			// --- parse the name ---
			for (int i = 0 ; i < triggerNames.length ; i++) {
				String triggerName = triggerNames[i];
				String triggerGroup = triggerGroups[i];

				quartzService.removeJobTrgger(triggerName, triggerGroup);
			}
		}
		
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setData( new HashMap() );
		
        // --- convert model to data format
		JSONObject jsonObj = JSONObject.fromObject(submitResult ); 

		/**
		 * defined the module and view handle
		 */
		ModelAndView mav = new ModelAndView();
        mav.setViewName("result");	// view name
        
        mav.addObject("json",jsonObj);
        
        logger.info(jsonObj.toString());
        return mav;	
	}
	
}
